package vn.vfriends.vbox.bean;

import java.io.IOException;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.Provider;
import vn.vfriends.vbox.provider.DropBoxProvider;
import vn.vfriends.vbox.provider.GoogleProvider;
import vn.vfriends.vbox.provider.StorageProvider;

/**
 *
 * @author tuancn
 */
@Named
@RequestScoped
public class StorageBean {
    
    private final Logger logger = LoggerFactory.getLogger(StorageBean.class);
    
    private Provider provider;

    public Provider getProvider() {
        return provider;
    }

    public void setProvider(Provider provider) {
        this.provider = provider;
    }
    
    public String cancelAction() {
        return "/home?faces-redirect=true";
    }
    
    public void registerAction() {
        try {
            StorageProvider storageProvider;
            if(provider == Provider.GOOGLE) {
                storageProvider = new GoogleProvider();
            } else {
                storageProvider = new DropBoxProvider();
            }
            
            String url = storageProvider.getAuthorizationUrl();
            FacesContext.getCurrentInstance().getExternalContext().redirect(url);
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Info", "Internal server error");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        }
    }
}
